<?php

namespace StudyBuddy;

/**
 *
 * Class for posting Question
 * or Answer to Twitter
 */
class Tweet {

    /**
     * Post the title of Question or Answer to Twitter
     * Usually this method is called as a shutdown_function
     * @todo if space allows add "prefixes" to Tweets
     * Prefixes will be strings, in translation...
     * 
     * @todo if space allows also add "via @ourname" to tweet if the
     * value of TWITTER_USERNAME exists if setting
     *
     * @param \StudyBuddy\Twitter $oTwitter
     * @param \StudyBuddy\Bitly $oBitly
     * @param object $Resource object of type Question or Answer
     * @return mixed null if exception was caught or array returned
     * by Twitter API
     */
    public function post(\StudyBuddy\Twitter $oTwitter, \StudyBuddy\Bitly $oBitly, $Resource) {
        d('cp');
        if (!($Resource instanceof \StudyBuddy\Question) && !($Resource instanceof \StudyBuddy\Answer)) {
            e('Resource not Question and not Answer');

            return;
        }

        $ret = null;

        /**
         * $title is already guaranteed to be
         * in utf-8
         */
        $title = $Resource['title'];

        /**
         * Short url from bit.ly is guaranteed
         * to be in utf-8
         */
        $short = $oBitly->getShortUrl($Resource->getUrl());

        /**
         * Our own url is in utf8 unless...
         * Unless this site is on some weird international
         * domain name that includes non-utf8 chars
         * This is super unlikely
         * We can assume that all components of
         * the tweet is already in utf-8
         */
        $url = ($short) ? $short : $Resource->getUrl(true);

        /**
         * Test what the length of tweet will be
         * if we concatinate title + space + url
         * 
         * @var int
         */
        $testLength = \mb_strlen($url . ' ' . $title, 'utf-8');
        if ($testLength > 140) {
            d('need to shorten title');
            $title = Utf8String::factory($title, 'utf-8', true)->truncate(139 - \mb_strlen($url, 'utf-8'))->valueOf();
            $text = $title . ' ' . $url;
        } else {
            $text = $title . ' ' . $url;
        }

        d('going to tweet this text: ' . $text);
        try {
            $ret = $oTwitter->postMessage($text);
        } catch (\Exception $e) {
            e('Tweet not sent because of exception: ' . $e->getMessage() . ' in file: ' . $e->getFile() . ' on line: ' . $e->getLine());
        }

        return $ret;
    }

}
